// edit.tsx
import React, { useState, useEffect, useCallback } from 'react';
import { Tabs, Modal, Form, Input, Select, DatePicker, Button, Space, message, Radio, Switch, Card, Row, Col, InputNumber } from 'antd';
import type { TabsProps } from 'antd';
import type { FormProps } from 'antd';
import { EditOutlined, LockOutlined, UserOutlined, PlusOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

import type { IMembers, IMemberFull } from '~/types/members';
import type { IRoles } from '../types/roles';

// 组件属性类型
interface MemberFormModalProps {
  visible: boolean;
  title: string;
  initialValues?: Partial<IMemberFull>;
  id?: number | null;
  loading: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

// 表单验证规则常量
const FORM_RULES = {
  fileNumber: [
    { required: true, message: '请输入档案号' }
  ],
  name: [
    { required: true, message: '请输入姓名' }
  ],
  sex: [
    { required: true, message: '请选择性别' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号' },
    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号码' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式' }
  ]
};

// 静态角色数据
const STATIC_ROLES: IRoles[] = [
  { id: 1, roleName: '管理员', roleCode: 'admin' },
  { id: 2, roleName: '医生', roleCode: 'doctor' },
  { id: 3, roleName: '护士', roleCode: 'nurse' },
  { id: 4, roleName: '健康管理师', roleCode: 'health_manager' }
];

// 提取共用的表单内容组件
const MemberFormContent = ({
  tabKey,
  showContent,
  toggleContent,
  isEditMode,
  roles
}: {
  tabKey: string;
  showContent: Record<string, boolean>;
  toggleContent: (key: string) => void;
  isEditMode: boolean;
  roles: IRoles[];
}) => {
  // 根据不同标签页key返回不同的内容
  const getTabSpecificContent = () => {
    switch (tabKey) {
      case '1':
        return (
          <>
            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name="fileNumber"
                  label="档案号"
                  rules={FORM_RULES.fileNumber}
                >
                  <Input placeholder="请输入档案号" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="姓名"
                  rules={FORM_RULES.name}
                >
                  <Input placeholder="请输入姓名" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name="idCard"
                  label="身份证号"
                  rules={FORM_RULES.idCard}
                >
                  <Input placeholder="请输入身份证号" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="phoneNumber"
                  label="手机号码"
                  rules={FORM_RULES.phoneNumber}
                >
                  <Input placeholder="请输入手机号码" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name="email"
                  label="邮箱"
                  rules={FORM_RULES.email}
                >
                  <Input placeholder="请输入邮箱" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="birthday"
                  label="出生日期"
                  rules={[{ required: true, message: '请选择出生日期' }]}
                >
                  <DatePicker
                    placeholder="请选择出生日期"
                    format="YYYY-MM-DD"
                    style={{ width: '100%' }}
                    disabledDate={(current) => current && current > dayjs().endOf('day')}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name="sex"
                  label="性别"
                  rules={FORM_RULES.sex}
                >
                  <Radio.Group style={{ width: '100%' }} optionType="button" buttonStyle="solid">
                    <Radio.Button value="男">男</Radio.Button>
                    <Radio.Button value="女">女</Radio.Button>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="remark"
                  label="备注"
                >
                  <Input.TextArea placeholder="请输入备注" rows={2} />
                </Form.Item>
              </Col>
            </Row>
          </>
        );
      case '2':
        return (
          <>
            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name={['TMemberInfo', 'maritalStatus']}
                  label="婚姻状况"
                >
                  <Select placeholder="请选择婚姻状况" allowClear>
                    <Select.Option value="1">未婚</Select.Option>
                    <Select.Option value="2">已婚</Select.Option>
                    <Select.Option value="3">离异</Select.Option>
                    <Select.Option value="4">丧偶</Select.Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['TMemberInfo', 'job']}
                  label="职业"
                >
                  <Input placeholder="请输入职业" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name={['TMemberInfo', 'educationDegree']}
                  label="教育程度"
                >
                  <Select placeholder="请选择教育程度" allowClear>
                    <Select.Option value="小学">小学</Select.Option>
                    <Select.Option value="初中">初中</Select.Option>
                    <Select.Option value="高中">高中</Select.Option>
                    <Select.Option value="大专">大专</Select.Option>
                    <Select.Option value="本科">本科</Select.Option>
                    <Select.Option value="硕士">硕士</Select.Option>
                    <Select.Option value="博士">博士</Select.Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['TMemberInfo', 'nativePlace']}
                  label="籍贯"
                >
                  <Input placeholder="请输入籍贯" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name={['TMemberInfo', 'healthMgrId']}
                  label="健康管理师"
                >
                  <Select placeholder="请选择健康管理师" allowClear>
                    {roles.map(role => (
                      <Select.Option key={role.id} value={role.id}>
                        {role.roleName}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['TMemberInfo', 'status']}
                  label="状态"
                >
                  <Select placeholder="请选择状态" allowClear>
                    <Select.Option value="0">正常</Select.Option>
                    <Select.Option value="1">冻结</Select.Option>
                    <Select.Option value="2">注销</Select.Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
          </>
        );
      case '3':
        return (
          <>
            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name={['TMemberDynamicinfo', 'height']}
                  label="身高(cm)"
                >
                  <InputNumber
                    placeholder="请输入身高"
                    style={{ width: '100%' }}
                    min={0}
                    max={250}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['TMemberDynamicinfo', 'weight']}
                  label="体重(kg)"
                >
                  <InputNumber
                    placeholder="请输入体重"
                    style={{ width: '100%' }}
                    min={0}
                    max={200}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name={['TMemberDynamicinfo', 'sbp']}
                  label="收缩压(mmHg)"
                >
                  <InputNumber
                    placeholder="请输入收缩压"
                    style={{ width: '100%' }}
                    min={0}
                    max={300}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['TMemberDynamicinfo', 'dbp']}
                  label="舒张压(mmHg)"
                >
                  <InputNumber
                    placeholder="请输入舒张压"
                    style={{ width: '100%' }}
                    min={0}
                    max={200}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name={['TMemberDynamicinfo', 'waistline']}
                  label="腰围(cm)"
                >
                  <InputNumber
                    placeholder="请输入腰围"
                    style={{ width: '100%' }}
                    min={0}
                    max={200}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['TMemberDynamicinfo', 'hipline']}
                  label="臀围(cm)"
                >
                  <InputNumber
                    placeholder="请输入臀围"
                    style={{ width: '100%' }}
                    min={0}
                    max={200}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={12}>
                <Form.Item
                  name={['TMemberDynamicinfo', 'thermometer']}
                  label="体温(℃)"
                >
                  <InputNumber
                    placeholder="请输入体温"
                    style={{ width: '100%' }}
                    min={0}
                    max={50}
                    step={0.1}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['TMemberDynamicinfo', 'breth']}
                  label="呼吸频率(次/分)"
                >
                  <InputNumber
                    placeholder="请输入呼吸频率"
                    style={{ width: '100%' }}
                    min={0}
                    max={100}
                  />
                </Form.Item>
              </Col>
            </Row>
          </>
        );
      case '4':
        return (
          <>
            <Row gutter={[24, 16]}>
              <Col span={24}>
                <Form.Item
                  name={['TMemberMedicalhistory', 'previousHistory']}
                  label="既往史"
                >
                  <Input.TextArea placeholder="请输入既往史" rows={3} />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={24}>
                <Form.Item
                  name={['TMemberMedicalhistory', 'familyHistory']}
                  label="家族史"
                >
                  <Input.TextArea placeholder="请输入家族史" rows={3} />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={24}>
                <Form.Item
                  name={['TMemberMedicalhistory', 'allergicHistory']}
                  label="过敏史"
                >
                  <Input.TextArea placeholder="请输入过敏史" rows={3} />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={24}>
                <Form.Item
                  name={['TMemberMedicalhistory', 'chronicDisease']}
                  label="慢性病"
                >
                  <Input.TextArea placeholder="请输入慢性病" rows={3} />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={[24, 16]}>
              <Col span={24}>
                <Form.Item
                  name={['TMemberMedicalhistory', 'medicalHistory']}
                  label="现病史"
                >
                  <Input.TextArea placeholder="请输入现病史" rows={3} />
                </Form.Item>
              </Col>
            </Row>
          </>
        );
      default:
        return null;
    }
  };

  return (
    <div style={{ padding: '0 40px' }}>
      {showContent[tabKey] ? (
        getTabSpecificContent()
      ) : (
        <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
          <div>交互演示内容已隐藏</div>
          <Space>
            <Button
              type="primary"
              onClick={() => toggleContent(tabKey)}
              style={{ marginTop: '16px' }}
            >
              显示内容
            </Button>
            <Button
              style={{ marginTop: '16px' }}
              onClick={() => {
                Object.keys(showContent).forEach(key => {
                  toggleContent(key);
                });
              }}
            >
              显示所有内容
            </Button>
          </Space>
        </div>
      )}
    </div>
  );
};

const MemberFormModal: React.FC<MemberFormModalProps> = ({
  visible,
  title,
  initialValues,
  loading,
  onCancel,
  onSuccess
}) => {
  const [activeTab, setActiveTab] = useState('1');
  const [showContent, setShowContent] = useState({
    1: true,
    2: true,
    3: true,
    4: true
  });
  const [form] = Form.useForm();
  const [roles, setRoles] = useState<IRoles[]>(STATIC_ROLES);
  const isEditMode = !!initialValues?.id;

  // 清理表单数据，确保没有undefined值和正确的日期格式
  const cleanFormData = (data: any) => {
    const cleaned = { ...data };

    // 处理日期格式
    const formatDate = (dateValue: any): string | null => {
      if (!dateValue) return null;
      try {
        if (dayjs.isDayjs(dateValue)) {
          return dateValue.format('YYYY-MM-DD');
        }
        if (typeof dateValue === 'string') {
          return dateValue.split('T')[0]; // 只取日期部分
        }
        return null;
      } catch (error) {
        console.error('日期格式转换错误:', error);
        return null;
      }
    };

    // 处理主要日期字段
    cleaned.birthday = formatDate(cleaned.birthday);
    cleaned.regTime = cleaned.regTime ? dayjs(cleaned.regTime).format('YYYY-MM-DDTHH:mm:ss.000Z') : new Date().toISOString();

    // 确保嵌套对象存在
    cleaned.TMemberInfo = cleaned.TMemberInfo || {};
    cleaned.TMemberDynamicinfo = cleaned.TMemberDynamicinfo || {};
    cleaned.TMemberMedicalhistory = cleaned.TMemberMedicalhistory || {};

    // 清理 undefined 和 null 值
    Object.keys(cleaned).forEach(key => {
      if (cleaned[key] === undefined || cleaned[key] === null) {
        if (key === 'id') {
          cleaned[key] = 0;
        } else if (typeof cleaned[key] === 'string') {
          cleaned[key] = '';
        } else if (typeof cleaned[key] === 'number') {
          cleaned[key] = 0;
        }
      }
    });

    return cleaned;
  };

  // 确保必需字段有值
  const ensureRequiredFields = (data: any) => {
    const currentTime = new Date().toISOString();

    return {
      fileNumber: data.fileNumber || `JK${dayjs().format('YYYYMMDD')}${Math.floor(Math.random() * 1000)}`,
      name: data.name || '',
      sex: data.sex || '男',
      idCard: data.idCard || '',
      phoneNumber: data.phoneNumber || '',
      regTime: data.regTime || currentTime,
      birthday: data.birthday || '1990-01-01',
      createtime: data.createtime || currentTime,
      updatetime: data.updatetime || currentTime,
      password: data.password || '123456', // 添加默认密码
      ...data
    };
  };

  // 表单提交处理 - 改为直接返回数据给父组件
  const handleFormSubmit: FormProps<IMemberFull>['onFinish'] = async (values) => {
    try {
      if (isEditMode && !initialValues?.id) {
        message.error('用户ID不存在，无法修改');
        return;
      }

      console.log('原始表单值:', values);

      // 清理表单数据
      const cleanedValues = cleanFormData(values);
      console.log('清理后的数据:', cleanedValues);

      // 确保必需字段
      const ensuredValues = ensureRequiredFields(cleanedValues);
      console.log('确保必需字段后的数据:', ensuredValues);

      // 构建返回给父组件的数据
      const resultData = {
        ...ensuredValues,
        // 移除嵌套对象，因为我们只关心顶层字段
        ...ensuredValues.TMemberInfo,
        ...ensuredValues.TMemberDynamicinfo,
        ...ensuredValues.TMemberMedicalhistory
      };

      // 移除嵌套对象字段
      delete resultData.TMemberInfo;
      delete resultData.TMemberDynamicinfo;
      delete resultData.TMemberMedicalhistory;

      // 模拟网络延迟
      setTimeout(() => {
        if (isEditMode) {
          message.success('会员修改成功！');
        } else {
          message.success('会员添加成功！');
        }
        // 将数据传递给父组件的成功回调
        onSuccess(resultData);
        onCancel();
      }, 500);

    } catch (error: any) {
      console.error(isEditMode ? '修改用户失败:' : '添加用户失败:', error);
      message.error(isEditMode ? '修改用户失败，请稍后重试' : '添加用户失败，请稍后重试');
    }
  };

  const onChange = (key: string) => {
    setActiveTab(key);
  };

  // 切换特定标签页内容的显示/隐藏
  const toggleContent = (tabKey: string) => {
    setShowContent(prev => ({
      ...prev,
      [tabKey]: !prev[tabKey]
    }));
  };

  // 标签页配置
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '基本信息',
      children: (
        <Card>
          <MemberFormContent
            tabKey="1"
            showContent={showContent}
            toggleContent={toggleContent}
            isEditMode={isEditMode}
            roles={roles}
          />
        </Card>
      ),
    },
    {
      key: '2',
      label: '详细信息',
      children: (
        <Card>
          <MemberFormContent
            tabKey="2"
            showContent={showContent}
            toggleContent={toggleContent}
            isEditMode={isEditMode}
            roles={roles}
          />
        </Card>
      ),
    },
    {
      key: '3',
      label: '动态信息',
      children: (
        <Card>
          <MemberFormContent
            tabKey="3"
            showContent={showContent}
            toggleContent={toggleContent}
            isEditMode={isEditMode}
            roles={roles}
          />
        </Card>
      ),
    },
    {
      key: '4',
      label: '病史信息',
      children: (
        <Card>
          <MemberFormContent
            tabKey="4"
            showContent={showContent}
            toggleContent={toggleContent}
            isEditMode={isEditMode}
            roles={roles}
          />
        </Card>
      ),
    },
  ];

  // 表单初始化与重置
  useEffect(() => {
    if (visible) {
      console.log('当前模式：', isEditMode ? '编辑模式' : '新增模式');
      console.log('传递的initialValues：', initialValues);

      if (initialValues) {
        // 设置表单值，处理嵌套对象和日期格式
        const formValues = {
          ...initialValues,
          // 确保日期字段是 dayjs 对象
          birthday: initialValues.birthday ? dayjs(initialValues.birthday) : dayjs('1990-01-01'),
          regTime: initialValues.regTime ? dayjs(initialValues.regTime) : dayjs(),
          createtime: initialValues.createtime ? dayjs(initialValues.createtime) : dayjs(),
          updatetime: initialValues.updatetime ? dayjs(initialValues.updatetime) : dayjs(),
          // 设置嵌套对象的值，确保不为undefined
          TMemberInfo: initialValues.TMemberInfo || {
            maritalStatus: 1,
            job: '',
            educationDegree: '',
            nativePlace: '',
            healthMgrId: 0,
            status: 0
          },
          TMemberDynamicinfo: initialValues.TMemberDynamicinfo || {
            height: 0,
            weight: 0,
            dbp: 0,
            sbp: 0,
            breth: 0,
            thermometer: 0,
            waistline: 0,
            hipline: 0
          },
          TMemberMedicalhistory: initialValues.TMemberMedicalhistory || {
            previousHistory: '',
            familyHistory: '',
            allergicHistory: '',
            medicalHistory: '',
            chronicDisease: ''
          },
        };

        console.log('设置表单值:', formValues);
        form.setFieldsValue(formValues);
      } else {
        // 新增模式下的默认值
        const formValues = {
          fileNumber: `JK${dayjs().format('YYYYMMDD')}${Math.floor(Math.random() * 1000)}`,
          name: '',
          sex: '男',
          idCard: '',
          phoneNumber: '',
          email: '',
          birthday: dayjs('1990-01-01'),
          regTime: dayjs(),
          remark: '',
          createtime: dayjs(),
          updatetime: dayjs(),
          TMemberInfo: {
            maritalStatus: 1,
            job: '',
            educationDegree: '本科',
            nativePlace: '',
            healthMgrId: 0,
            status: 0
          },
          TMemberDynamicinfo: {
            height: 0,
            weight: 0,
            dbp: 0,
            sbp: 0,
            breth: 0,
            thermometer: 0,
            waistline: 0,
            hipline: 0
          },
          TMemberMedicalhistory: {
            previousHistory: '',
            familyHistory: '',
            allergicHistory: '',
            medicalHistory: '',
            chronicDisease: ''
          }
        };

        console.log('新增模式默认值:', formValues);
        form.setFieldsValue(formValues);
      }
    }
  }, [visible, initialValues, form, isEditMode]);

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      footer={null}
      destroyOnClose={true}
      maskClosable={false}
      width={800}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleFormSubmit}
        validateMessages={{ required: '${label}是必填项' }}
      >
        <Tabs
          activeKey={activeTab}
          items={items}
          onChange={onChange}
          type="card"
          size="large"
        />

        <Form.Item style={{ textAlign: 'center', marginTop: 32 }}>
          <Space size="middle">
            <Button onClick={onCancel} style={{ width: 120 }}>取消</Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              icon={isEditMode ? <EditOutlined /> : <PlusOutlined />}
              style={{ width: 140 }}
            >
              {isEditMode ? '立即修改' : '立即添加'}
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default MemberFormModal;